package io.github.wppli.webcocket.interceptor;

import cc.jq1024.middleware.token.service.ITokenService;
import io.github.wppli.types.security.util.CacheService;
import lombok.AllArgsConstructor;
import okhttp3.WebSocket;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.util.Map;

@Component
@AllArgsConstructor
public class JwtHandshakeInterceptor implements HandshakeInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtHandshakeInterceptor.class);
    private final ITokenService tokenService;

    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
                                   @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) throws Exception {

        // 从请求头或参数中获取 Token
        if (request instanceof ServletServerHttpRequest) {
            URI uri = request.getURI();
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 或者从 Header 获取（推荐）
            String token = servletRequest.getServletRequest().getHeader("Authorization");
            log.info("uri: {} token:{}", uri, token);
            if (token == null || token.isEmpty()) {
                return true;
            }
            // 验证 Token
            try {
                String userId = tokenService.decode(token).getSubject();
                // 将用户信息存入 WebSocket 会话属性
                attributes.put("userId", userId);
                return true; // 允许握手
            } catch (Exception e) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false; // 拒绝连接
            }
        }
        return false;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
                               @NotNull WebSocketHandler wsHandler, Exception exception) {
        // 握手成功后调用（可选）
    }

}